<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/public/BaseCms.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/public/Attachment.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/config/globalconfig.php");

class Products extends BaseCms
{
    public $tb_name = "product";
    public $currentPage = 1;
    public $pageSize = 20;
    public $totalDatas = 0;
    public $totalPages = 1;
    public $productDatas;
    public $lastData;
    public $nextData;
    public $pictures;

    function __construct()
    {
        parent::__construct($this->tb_name);
    }

    /**
     * 处理数据上传
     * @return array|bool
     */
    function upload_mulit()
    {
        if (!file_exists(UPLOAD)) {
            mkdir(UPLOAD);
        }
        $i = 0;
        $result = array();
        foreach ($_FILES["pictures"]["error"] as $key => $error) {
            $temp = $_FILES["pictures"][$i++];
            if ($error == UPLOAD_ERR_OK) {
                $re_file = $this->upload($temp, "product/");
                array_push($result, $re_file);
            }
        }
        return $result;
    }

    /**
     * 初始化数据
     * @param $category_id 分类id
     * @param int $page_size 每页大小
     * @param int $current_page 当前页
     */
    function init($category_id, $current_page = 1, $page_size = 20)
    {
        $this->currentPage = $current_page;
        $this->pageSize = $page_size;
        $condition = ["id_data_category" => $category_id];
        $orderBy = ["top_show"=>"asc","index_show"=>"asc","created_date" => "desc", "id_product" => "desc"];
        $this->productDatas = $this->findByPage($this->currentPage, $this->pageSize, $condition, $orderBy);
        $this->totalDatas = $this->count($condition);
        $this->totalPages = $this->totalDatas % $this->pageSize == 0 ? (int)($this->totalDatas / $this->pageSize) : (int)($this->totalDatas / $this->pageSize) + 1;
    }

    /**
     * 根据id获取数据
     * @param $product_id 产品Id
     */
    function loadById($product_id)
    {
        $condition = ["id_product" => $product_id];
        $orderBy = ["created_date" => "desc", "id_product" => "desc"];
        $this->productDatas = $this->findOne($condition);
        $condition = ["id_product" => [$this->param_value_key => $product_id, $this->param_operation => "<"]];
        $this->lastData = $this->findOne($condition, $orderBy);
        $orderBy = ["created_date" => "desc", "id_product" => "asc"];
        $condition = ["id_product" => [$this->param_value_key => $product_id, $this->param_operation => ">"]];
        $this->nextData = $this->findOne($condition, $orderBy);
        $attachment = new Attachment();
        $condition = ["business_no" => $this->productDatas["dataNo"]];
        $orderBy = ["data_sort" => "asc"];
        $this->pictures = $attachment->findList($condition, $orderBy);
    }


}